<?php declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\Designer;
use app\common\helper\ConstBase;
use app\common\model\CasesCategory;
use app\common\model\House;
use think\facade\Log;

class HouseService
{
    /**
     * 列表
     * @return void
     */
    public function getDataList($keywords, $pageSize)
    {
        $model = new House();
        return $model
            ->where(function ($query) use ($keywords) {
                if($keywords){
                    $query->where('name', 'like', $keywords .'%');
                }
            })
            ->order(['sort'=>'desc','id'=>'desc'])
            ->paginate($pageSize);
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        try {
            $model = new House();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit house error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 操作
     * @return void
     */
    public function action($id, $type){
        $model = new House();
        try {
            $status = $type ? 1:0;
            $model->where('id', $id)->update(['status'=>$status, 'update_time'=>time()]);

            return json(['code'=>0, 'msg'=>'操作成功']);
        } catch (\Exception $e) {
            Log::error("action House {$id} error:". $e->getMessage());

            return json(['code'=>1, 'msg'=>'操作失败，'. $e->getMessage()]);
        }
    }

    /**
     * 删除记录
     * @param $id
     * @return void
     */
    public function delete($id)
    {
        try {
            $ids = !is_array($id) ? [$id]:$id;
            $model = new House();
            $model::destroy($id);

            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error("delete House " .json_encode($ids). " failed：".$e->getMessage());

            return json(['code'=>1, 'msg'=>'删除失败']);
        }
    }

    /**
     * 查询一条记录
     * @param $id
     * @return Article|array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne($id)
    {
        $model = new House();
        return $model->find($id);
    }
}